package edu.friday.controller;

import edu.friday.common.result.RestResult;
import edu.friday.common.core.text.Convert;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.vo.GenTableColumnVO;
import edu.friday.model.vo.GenTableVO;
import edu.friday.service.GenTableColumnService;
import edu.friday.service.GenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;


/**
 * 代码生成 操作处理
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController {
    @Autowired
    private GenTableService genTableService;

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping("/list")
    public TableDataInfo genList(GenTableVO genTable, Pageable page) {
        int pageNum = page.getPageNumber() - 1;
        pageNum = pageNum <= 0 ? 0 : pageNum;
        page = PageRequest.of(pageNum, page.getPageSize());
        return genTableService.selectGenTableList(genTable, page);
    }

    /**
     * 修改代码生成业务
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:query')")
    @GetMapping(value = "/{talbleId}")
    public RestResult getInfo(@PathVariable Long talbleId) {
        return genTableService.selectGenTableById(talbleId);
    }

    /**
     * 查询数据库列表
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping("/db/list")
    public TableDataInfo dataList(GenTableVO genTable, Pageable page ) {
        int pageNum = page.getPageNumber() - 1;
        pageNum = pageNum <= 0 ? 0 : pageNum;
        page = PageRequest.of(pageNum, page.getPageSize());
        return genTableService.selectDbTableList(genTable,page);
    }

    /**
     * 查询数据表字段列表
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @GetMapping(value = "/column/{talbleId}")
    public TableDataInfo columnList(Long tableId) {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumnVO> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:list')")
    @PostMapping("/importTable")
    public RestResult importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTableVO> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return RestResult.success();
    }

    /**
     * 修改保存代码生成业务
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:edit')")
    @PutMapping
    public RestResult editSave(@Validated @RequestBody GenTableVO genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return RestResult.success();
    }

//    @PreAuthorize("@ss.hasPermi('tool:gen:remove')")
    @DeleteMapping("/{tableIds}")
    public RestResult remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return RestResult.success();
    }

    /**
     * 预览代码
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:preview')")
    @GetMapping("/preview/{tableId}")
    public RestResult preview(@PathVariable("tableId") Long tableId) throws IOException {
        return genTableService.previewCode(tableId);
    }

    /**
     * 生成代码
     */
    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.generatorCode(tableName);
        genCode(response, data);
    }

    /**
     * 批量生成代码
     */
//    @PreAuthorize("@ss.hasPermi('tool:gen:code')")
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.generatorCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        String timestamp = Calendar.getInstance().getTime().toString();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi"+timestamp+".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}